import Vue from 'vue'
import VueRouter from 'vue-router'
import _404 from '@/views/404'

// 重写官方的push方法
const originPush = VueRouter.prototype.push;
VueRouter.prototype.push = function(location, resolve, reject) {
  if (resolve || reject) {
    return originPush.call(this, location, resolve, reject)
  }
  return originPush.call(this, location).catch(e => e);
}

Vue.use(VueRouter)

const annoUrls = ['/login']

// 是否拉取过权限
let flag = false;

const routes = [{
  path: '/',
  redirect: '/home'
}, {
  path: '/login',
  name: 'login',
  component: () => import('@/views/login')
}]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

let user = null;
let authorization = null;

router.beforeEach((to, from, next) => {
  let index = annoUrls.findIndex(item => to.path == item);
  if (index != -1) {
    next();
    return;
  }
  if (!user || !authorization) {
    try {
      user = JSON.parse(sessionStorage.getItem('user'));
      authorization = JSON.parse(sessionStorage.getItem('authorization'));
    } catch (e) {
      next('/login');
      return;
    }
    if (!user || !authorization) {
      next('/login');
      return;
    }
    if (!flag) {
      createRouter(authorization);
      flag = true;
      next({...to, replace: true});
    }
  }
  next();
})

// 生成路由
function createRouter(authorization) {
  let routers = [{
    path: '/home',
    name: 'home',
    component: () => import(`@/views/home`),
    children: authorization
  }, {
    path: '*',
    name: '_404',
    component: _404
  }];
  authorization.forEach(item => {
    let component = item.component
    item.component = () => import(`@/views/${component}`);
  });
  router.addRoutes(routers);
}

export default router
